package model

import (
	"fmt"
	"goWebStudy/web_db1/utils"
)

// Student 结构体
type Student struct {
	Id    int
	Name  string
	Age   int
	Class string
}

// Add 添加Student的方法yi
func (student *Student) addStudent() error {
	//写sql语句
	sqlStr := "insert into students(id,name,age,class) values(?,?,?,?)"
	//预编译
	inStmt, err := utils.Db.Prepare(sqlStr)
	if err != nil {
		fmt.Println("预编译出现异常：", err)
		return err
	}
	//3.执行
	_, err = inStmt.Exec(5, "朱宗宁", 25, "计科二班")
	if err != nil {
		fmt.Println("执行出现异常：", err)
		return err
	}
	return err
}

// Add 添加Student的方法2
func (student *Student) addStudent2() error {
	//写sql语句
	sqlStr := "insert into students(id,name,age,class) values(?,?,?,?)"
	//3.执行
	_, err := utils.Db.Exec(sqlStr, 6, "朱宗宁", 26, "计科二班")
	if err != nil {
		fmt.Println("执行出现异常：", err)
		return err
	}
	return err
}

// 查询一条记录
func (student *Student) GetStudentByID() (*Student, error) {
	//写sql语句
	sqlStr := "select id,name,age,class from students where id = ?"
	//执行sql
	row := utils.Db.QueryRow(sqlStr, student.Id)
	//声明
	var id int
	var name string
	var age int
	var class string
	err := row.Scan(&id, &name, &age, &class)
	if err != nil {
		return nil, err
	}
	u := &Student{
		Id:    id,
		Name:  name,
		Age:   age,
		Class: class,
	}
	return u, err
}

// GetStudents 获取数据库中所有的记录
func (student *Student) GetStudents() ([]*Student, error) {
	//写sql语句
	sqlStr := "select id,name,age,class from students"
	//执行
	rows, err := utils.Db.Query(sqlStr)
	if err != nil {
		return nil, err
	}
	//创建要返回d切片
	var students []*Student
	//因为是查询多条记录，所以就不使用scan函数来赋值了而是使用Next(准备用于Scan方法的下一行结果。
	//如果成功会返回真，如果没有下一行或出现错误会返回假。Err应该被调用以区分这两种情况
	for rows.Next() {
		//声明
		var id int
		var name string
		var age int
		var class string
		err := rows.Scan(&id, &name, &age, &class)
		if err != nil {
			return nil, err
		}
		u := &Student{
			Id:    id,
			Name:  name,
			Age:   age,
			Class: class,
		}
		students = append(students, u)
	}
	return students, err
}
